package org.zhaozhen.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录资源拦截器
 */
@Component //注意
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //1.校验token是否有值
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)) {
            //2 如果有值，从redis获取登录人，看是否失效（30分钟）
            Object loginTmp = redisTemplate.opsForValue().get(token);
            // 2.1 查到登录用户
            if (loginTmp != null) {
                // 2.2 放行 刷新过期时间
                redisTemplate.opsForValue().set(token, loginTmp, 30, TimeUnit.MINUTES);

                //@TODO 权限校验  即使你登陆了，我也还要看你有没有权限访问资源
                return true; //放行
            }
        }
        //1.1.没值，就报错 ？？ 阻止放行
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false; //阻止放行
    }
}
